<?php

namespace haoleke\utils\encrypt;

/**
 * 对称加密
 */
class Aes256Cbc
{
    private $encryptionKey;
    private $cipherMethod = 'aes-256-cbc';

    public function __construct($key) {
        $this->encryptionKey = $key;
    }

    /**
     * 加密数据
     */
    public function encrypt($data) {
        if (empty($data)) {
            return $data;
        }

        // 生成初始化向量
        $ivLength = openssl_cipher_iv_length($this->cipherMethod);
        $iv = openssl_random_pseudo_bytes($ivLength);

        // 加密数据
        $encrypted = openssl_encrypt(
            $data,
            $this->cipherMethod,
            $this->encryptionKey,
            0,
            $iv
        );

        return [
            'encrypted' => $encrypted,
            'iv' => bin2hex($iv)
        ];
    }

    /**
     * 解密数据
     */
    public function decrypt($encryptedData, $iv) {
        if (empty($encryptedData)) {
            return $encryptedData;
        }

        return openssl_decrypt(
            $encryptedData,
            $this->cipherMethod,
            $this->encryptionKey,
            0,
            hex2bin($iv)
        );
    }
}